import { getUser } from "@/functions/get-user";
{{#if (eq payments "polar") }}
import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client";
import { getPayment } from "@/functions/get-payment";
{{/if}}
{{#if (eq api "trpc") }}
import { useTRPC } from "@/utils/trpc";
import { useQuery } from "@tanstack/react-query";
{{/if}}
{{#if (eq api "orpc") }}
import { orpc } from "@/utils/orpc";
import { useQuery } from "@tanstack/react-query";
{{/if}}
import { createFileRoute, redirect } from "@tanstack/react-router";

export const Route = createFileRoute("/dashboard")({
  component: RouteComponent,
  beforeLoad: async () => {
    const session = await getUser();
    {{#if (eq payments "polar") }}
    const customerState = await getPayment();
    return { session, customerState };
    {{else}}
    return { session };
    {{/if}}
  },
  loader: async ({ context }) => {
    if (!context.session) {
      throw redirect({
        to: "/login",
      });
    }
  },
});

function RouteComponent() {
  const { session{{#if (eq payments "polar") }}, customerState{{/if}} } = Route.useRouteContext();

  {{#if (eq api "trpc") }}
  const trpc = useTRPC();
  const privateData = useQuery(trpc.privateData.queryOptions());
  {{/if}}
  {{#if (eq api "orpc") }}
  const privateData = useQuery(orpc.privateData.queryOptions());
  {{/if}}

  {{#if (eq payments "polar") }}
  const hasProSubscription = (customerState?.activeSubscriptions?.length ?? 0) > 0;
  // For debugging: console.log("Active subscriptions:", customerState?.activeSubscriptions);
  {{/if}}

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Welcome {session?.user.name}</p>
      {{#if (eq api "trpc") }}
      <p>API: {privateData.data?.message}</p>
      {{else if (eq api "orpc") }}
      <p>API: {privateData.data?.message}</p>
      {{/if}}
      {{#if (eq payments "polar") }}
      <p>Plan: {hasProSubscription ? "Pro" : "Free"}</p>
      {hasProSubscription ? (
        <Button
          onClick={async function handlePortal() {
            await authClient.customer.portal();
          }}
        >
          Manage Subscription
        </Button>
      ) : (
        <Button
          onClick={async function handleUpgrade() {
            await authClient.checkout({ slug: "pro" });
          }}
        >
          Upgrade to Pro
        </Button>
      )}
      {{/if}}
    </div>
  );
}